# @Time : 2020/12/29 9:26
# @Author : Fioman 
# @Phone : 13149920693
"""
xml 解析，解析xml文件。 xml文件的书写获取或者得到
"""
import time
from xml.dom.minidom import parse, Document
from settings import  MSG_RECV_PATH,RECIPE_PARAMS_PATH,ASK_MSG_PATH,MSG_SEND_PATH


def parse_recv_msg(msgRecv):
    # 1.先将消息写入到文件当中
    write_recv_message(msgRecv)
    dom = parse(MSG_RECV_PATH)
    rootNode = dom.documentElement
    msgNameNode = rootNode.getElementsByTagName("messagename")[0]
    transactionNode = rootNode.getElementsByTagName("transactionid")[0]
    bodyDict = {}
    bodyNode = rootNode.getElementsByTagName("body")[0]
    msgName = msgNameNode.childNodes[0].data
    if msgName == "Job Data Download":
        write_recipe_params(msgRecv)
        print("接收到Job Data Download 消息:")
        bodyDict = {}
        for node in bodyNode.childNodes:
            # if node.nodeName == "recipe_name":
            #     bodyDict[node.nodeName] = node.childNodes[0].data
            #     continue

            if node.nodeName == "lot_id":
                bodyDict[node.nodeName] = node.childNodes[0].data
                continue

            if node.nodeName == "recipe_parameter_list":
                for d in node.childNodes:
                    if d.nodeName == "parameter":
                        for d1 in d.childNodes:
                            if d1.nodeName == "parameter_name":
                                dictKey = d1.childNodes[0].data
                            if d1.nodeName == "parameter_value":
                                dictVal = d1.childNodes[0].data
                        else:
                            bodyDict[dictKey] = dictVal
    else:
        for node in bodyNode.childNodes:
            if node.nodeName != "#text" and node.nodeName != "user_id":
                bodyDict[node.nodeName] = node.childNodes[0].data

    retNode = rootNode.getElementsByTagName("returncode")[0]
    retCode = retNode.childNodes[0].data



    if "Reply" not in msgName:
        transactionId = transactionNode.childNodes[0].data
    else:
        transactionId = get_transaction_id()

    print(msgName,bodyDict,retCode,transactionId)

    return msgName, bodyDict, retCode, transactionId


def write_recv_message(msgRecv):
    """
    将接收到的消息写入到文件message_recv.xml中，以便后续的解析
    :param msgRecv: 接收到的消息，包括消息头和消息结尾char(2)和char(3)
    :return:
    """
    with open(MSG_RECV_PATH, "wb") as f:
        f.write(msgRecv[1:-1])

def write_recipe_params(msgRecv):
    with open(RECIPE_PARAMS_PATH, "wb") as f:
        f.write(msgRecv[1:-1])


def get_now_time_str():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


def get_transaction_id():
    nowSecond = time.time()
    lastThree = str(nowSecond).split(".")[1][:3]
    now = time.strftime("%Y%m%d%H%M%S", time.localtime(nowSecond))
    transactionId = now + lastThree
    return transactionId


def pack_send_msg(msgName, bodyDict, retCode, transactionId=None):
    doc = Document()  # 在内存中创建一个空的文档
    root = doc.createElement("message")  # 创建根节点
    doc.appendChild(root)  # 将根节点添加到文件对象中

    # 然后将head的消息和body的消息以及ret的消息填入
    headNode = doc.createElement("header")  # 创建head节点
    msgNameNode = doc.createElement("messagename")  # 创建消息名称节点
    msgNameNode.appendChild(doc.createTextNode(msgName))  # 消息名称的文字节点
    if transactionId is None:
        transactionIdUsed = get_transaction_id()
    else:
        transactionIdUsed = transactionId
    idNode = doc.createElement("transactionid")
    idNode.appendChild(doc.createTextNode(transactionIdUsed))
    headNode.appendChild(msgNameNode)
    headNode.appendChild(idNode)
    # 头部节点创建完成

    bodyNode = doc.createElement("body")
    if msgName == "Recipe Body Reply":
        recipeNameNode = doc.createElement("recipe_name")
        recipeDataListNode = doc.createElement("recipe_body_list")
        recipeName = bodyDict[0]
        for item in bodyDict[1]:
            recipeListNode = doc.createElement("recipe_body")
            dataItemNode = doc.createElement("data_item")
            dataValueNode = doc.createElement("data_value")
            dataItemNode.appendChild(doc.createTextNode(item[0]))
            dataValueNode.appendChild(doc.createTextNode(item[1]))
            recipeListNode.appendChild(dataItemNode)
            recipeListNode.appendChild(dataValueNode)
            recipeDataListNode.appendChild(recipeListNode)
        recipeNameNode.appendChild(doc.createTextNode(recipeName))
        bodyNode.appendChild(recipeNameNode)
        bodyNode.appendChild(recipeDataListNode)
    elif msgName == "Trace Data Reply":
        traceDataListNode = doc.createElement("trace_data_list")
        for item in bodyDict:
            traceListNode = doc.createElement("trace_data")
            dataNoNode = doc.createElement("data_no")
            dataItemNode = doc.createElement("data_item")
            dataValueNode = doc.createElement("data_value")
            dataNoNode.appendChild(doc.createTextNode(item[0]))
            dataItemNode.appendChild(doc.createTextNode(item[1]))
            dataValueNode.appendChild(doc.createTextNode(str(item[2])))
            traceListNode.appendChild(dataNoNode)
            traceListNode.appendChild(dataItemNode)
            traceListNode.appendChild(dataValueNode)
            traceDataListNode.appendChild(traceListNode)
        bodyNode.appendChild(traceDataListNode)
    elif msgName == "Process Data Report":
        rePortTypeNode = doc.createElement("report_type")
        judgeTypeNode = doc.createElement("judge")
        proceNameNode = doc.createElement("proc_name")
        rePortTypeNode.appendChild(doc.createTextNode(bodyDict[0]))
        judgeTypeNode.appendChild(doc.createTextNode(bodyDict[1]))
        proceNameNode.appendChild(doc.createTextNode(bodyDict[2]))

        procDataListNode = doc.createElement("proc_data_list")
        for item in bodyDict[3]:
            procDataNode = doc.createElement("proc_data")
            dataItemNode = doc.createElement("data_item")
            dataValueNode = doc.createElement("data_value")
            dataItemNode.appendChild(doc.createTextNode(item[0]))
            dataValueNode.appendChild(doc.createTextNode(item[1]))
            procDataNode.appendChild(dataItemNode)
            procDataNode.appendChild(dataValueNode)
            procDataListNode.appendChild(procDataNode)
        bodyNode.appendChild(rePortTypeNode)
        bodyNode.appendChild(judgeTypeNode)
        bodyNode.appendChild(proceNameNode)
        bodyNode.appendChild(procDataListNode)

    else:
        if len(bodyDict.items()) == 0:
            bodyNode.appendChild(doc.createTextNode(" "))
        else:
            for element, value in bodyDict.items():
                node = doc.createElement(element)
                node.appendChild(doc.createTextNode(value))
                bodyNode.appendChild(node)

    retNode = doc.createElement("return")
    for element, value in retCode.items():
        node = doc.createElement(element)
        if value != "":
            node.appendChild(doc.createTextNode(value))
        retNode.appendChild(node)

    # 然后将head_node,body_node,ret_node加到根节点root节点上面去
    root.appendChild(headNode)
    root.appendChild(bodyNode)
    root.appendChild(retNode)

    if msgName == "Are You There Request":
        fp1 = open(ASK_MSG_PATH, 'w', encoding='UTF-8')
        doc.writexml(fp1, indent='', addindent='\t', newl='\n', encoding='UTF-8')
        fp1.close()
    else:
        fp2 = open(MSG_SEND_PATH, 'w', encoding="UTF-8")
        doc.writexml(fp2, indent='', addindent='\t', newl='\n', encoding='UTF-8')
        fp2.close()


if __name__ == '__main__':

    with open(MSG_RECV_PATH, "rb") as f:
        msgRecv = f.read()

    parse_recv_msg(msgRecv)